package de.velvettear.squirrel.adapter;

import java.util.Vector;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import de.velvettear.squirrel.R;
import de.velvettear.squirrel.kernel.Host;

public class HostAdapter extends ArrayAdapter {
	
	private Context context;
	
	private Vector<Host> hosts;
				
	public HostAdapter(Context context, int layout, int textViewResourceId, Vector<Host> hosts) {
		super(context, layout, textViewResourceId, hosts);
		this.context = context;
		this.hosts = hosts;
	}
	
	@Override
	public int getCount() {
		return hosts.size();
	}

	@Override
	public Host getItem(int position) {
		return hosts.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup viewGroup) {
		HostViewHolder viewHolder;
		Host host = hosts.get(position);		
		if (convertView == null) {
			LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = inflater.inflate(R.layout.listview_hosts, null);
			
			viewHolder = new HostViewHolder();
			viewHolder.tv_ip = (TextView) convertView.findViewById(R.id.listview_hosts_ip);
			viewHolder.tv_name = (TextView) convertView.findViewById(R.id.listview_hosts_name);	
			viewHolder.iv_reachable = (ImageView) convertView.findViewById(R.id.listview_hosts_reachable);
			viewHolder.icon_check = convertView.getResources().getDrawable(R.drawable.icon_check);
			viewHolder.icon_fail = convertView.getResources().getDrawable(R.drawable.icon_fail);
			
			convertView.setTag(viewHolder);
		} else {
			viewHolder = (HostViewHolder) convertView.getTag();
		}		
				
		viewHolder.tv_ip.setText(host.m_sIP);				
		viewHolder.tv_name.setText(host.m_sName);			
		if (host.m_bReachable) {
			viewHolder.iv_reachable.setImageDrawable(viewHolder.icon_check);
		} else {
			viewHolder.iv_reachable.setImageDrawable(viewHolder.icon_fail);
		}
		
		return convertView;	
	}
	
	static class HostViewHolder {
		View convertView;
		TextView tv_ip;
		TextView tv_name;
		ImageView iv_reachable;
		Drawable icon_check;
		Drawable icon_fail;
	}
	
}
